package java2;

/**
 * @Author 不知名网友鑫
 * @Date 2022/5/5
 * Runnable方式实现多线程，使用同步代码块来解决线程安全问题。
 **/
public class ThreadSafeTest {
    public static void main(String[] args) {
        Windows w = new Windows();
        Thread t1 = new Thread(w);
        Thread t2 = new Thread(w);
        t1.start();
        t2.start();
    }

}
class Windows implements Runnable{
    private int ticket = 100;
    Object obj = new Object();
    @Override
    public void run() {
        while(true) {
            //同步代码块，[同步监视器推荐使用this]
            synchronized (this) {
                if (ticket > 0) {
                    System.out.println(Thread.currentThread().getName() + ":" + ticket);
                    ticket--;
                } else {
                    break;
                }
            }
        }
    }
}
